// 定义接口返回数据的类型
interface ApiResponse<T> {
  code: string;
  msg: string;
  data: T;
}

export interface SearchParams {
  keyword: string;
  page?: number;
  userId?: string;
}

export interface SearchResult {
  id: string | null;
  userId: string;
  keyword: string;
  proxyId: string;
  proxyName: string;
  apiUrl: string | null;
  vodId: string;
  vodName: string;
  vodPic: string;
  typeName: string;
  vodYear: string;
  vodRemarks: string;
}

export interface StreamSearchResult {
  type: 'start' | 'data' | 'end' | 'error';
  event?: string;
  data?: SearchResult;
  error?: string;
}

/**
 * 搜索接口
 * @param params 搜索参数
 * @returns Promise<ApiResponse<SearchResult[]>>
 */
export async function search(params: SearchParams): Promise<{ code: number; msg: string | null; data: SearchResult[] }> {
  const res = await fetch('/api/search/search', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params),
  });
  return res.json();
}

/**
 * 流式搜索接口
 * @param params 搜索参数
 * @param onMessage 消息处理回调
 * @returns 关闭流的函数
 */
export function streamSearch(
  params: SearchParams,
  onMessage: (result: StreamSearchResult) => void
): () => void {
  const controller = new AbortController();
  const { signal } = controller;

  console.log('streamSearch params:', params);

  const queryParams = new URLSearchParams({
    keyword: params.keyword,
    page: params.page?.toString() || '1'
  });

  const url = `/api/search/stream?${queryParams.toString()}`;
  console.log('Request URL:', url);

  // 发送开始消息
  onMessage({ type: 'start' });

  fetch(url, {
    method: 'GET',
    headers: { 
      'Content-Type': 'text/event-stream',
      'Accept': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      ...(params.userId ? { 'userId': params.userId } : {})
    },
    signal,
  }).then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const reader = response.body?.getReader();
    const decoder = new TextDecoder();
    let buffer = '';
    let currentEvent = '';

    function processChunk(chunk: string) {
      const lines = chunk.split('\n');
      for (const line of lines) {
        if (line.trim() === '') continue;
        
        if (line.startsWith('event:')) {
          currentEvent = line.slice(6).trim();
          continue;
        }
        
        if (line.startsWith('data:')) {
          try {
            // 提取 data: 后的内容，去掉前后空白
            const jsonStr = line.replace(/^data:\s*/, '').trim();
            const data = JSON.parse(jsonStr);
            onMessage({ 
              type: 'data', 
              event: currentEvent,
              data 
            });
          } catch (e) {
            console.error('Failed to parse SSE data:', e, 'Line:', line, 'jsonStr:', jsonStr);
          }
        }
      }
    }

    function readChunk() {
      reader?.read().then(({ done, value }) => {
        if (done) {
          onMessage({ type: 'end' });
          return;
        }

        const chunk = decoder.decode(value, { stream: true });
        buffer += chunk;
        
        const lines = buffer.split('\n');
        buffer = lines.pop() || '';

        for (const line of lines) {
          processChunk(line);
        }

        readChunk();
      }).catch(error => {
        if (error.name === 'AbortError') {
          return;
        }
        onMessage({ type: 'error', error: error.message });
      });
    }

    readChunk();
  }).catch(error => {
    if (error.name === 'AbortError') {
      return;
    }
    onMessage({ type: 'error', error: error.message });
  });

  return () => controller.abort();
}

// 使用示例：
// const result = await search({ keyword: '电影', page: 1, pageSize: 10 }); 

// 流式搜索使用示例：
// const stopStream = streamSearch(
//   { keyword: '电影' },
//   (result) => {
//     switch (result.type) {
//       case 'start':
//         console.log('开始搜索');
//         break;
//       case 'data':
//         if (result.data) {
//           setData(prev => [...prev, result.data!]);
//         }
//         break;
//       case 'end':
//         console.log('搜索结束');
//         break;
//       case 'error':
//         console.error('发生错误:', result.error);
//         break;
//     }
//   }
// );
// 
// // 当需要停止流时调用
// stopStream(); 